/*tcp服务器*/
#include <stdio.h>
#include <arpa/inet.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/epoll.h>
#include <errno.h>

const int PORT = 9505;
const char SERVER_IP[15] = {"127.0.0.1"};

int main() {

    //TCP 参数： SOCK_STREAM、IPPROTO_TCP ；UDP参数： SOCK_DGRAM 、IPPTOTO_UDP
    int sockfd = -1;
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0) {
        printf("%s\n", "socket 套接字文件初始化失败");
        return -1;
    } else {
        printf("socket init..OK........\n");
    }

    int received_data_len,send_data_len;
    char buffer[BUFSIZ];//缓冲区大小
    struct sockaddr_in server_addr;
    //对内存清零
    memset(&server_addr, 0, sizeof(server_addr));

    server_addr.sin_family = AF_INET; //选择IPV4地址类型
    server_addr.sin_port = htons(PORT); //选择端口号
    server_addr.sin_addr.s_addr = inet_addr(SERVER_IP); //选择IP地址
    int server_addr_len = sizeof(server_addr);

    // 连接服务端端
    if (connect(sockfd, (struct sockaddr *) &server_addr, server_addr_len) < 0) {
        printf("连接到服务端失败,相关错误：%s\n", strerror(errno));
        return -1;
    } else {
        printf("connet %s OK........\n",SERVER_IP);
    }

    // 阻塞处理消息
    while (1) {
        received_data_len=recv(sockfd,buffer,BUFSIZ,0);
        printf("接收到的数据长度:%d\t,结果：%s\n",received_data_len,buffer);
        scanf("%s",buffer);
        send_data_len=send(sockfd,buffer,strlen(buffer),0);
        printf("已发送的数据长度:%d\n",send_data_len);
    }
    close(sockfd);//关闭套接字
    return 0;
}
